package com.example.painta;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    int sharpe = 0;
    int colorIndex = 0;
    int[] colors = {Color.WHITE, Color.CYAN, Color.YELLOW};
    DrawView drawView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        drawView = new DrawView(this);
        setContentView(drawView);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                //改变形状
                sharpe = (sharpe + 1) % 3;
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                colorIndex = (colorIndex + 1) % 3;
                break;
        }
        drawView.postInvalidate();
       return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                drawView.x = (int) event.getX();
                drawView.y = (int) event.getY() - 100;
                break;
            case MotionEvent.ACTION_MOVE:
                drawView.x = (int) event.getX();
                drawView.y = (int) event.getY() - 100;
                break;
            case MotionEvent.ACTION_UP:
                drawView.x = -360;
                drawView.y = -360;
                break;
        }drawView.postInvalidate();
        return super.onTouchEvent(event);

    }

    class DrawView extends View {
        Paint paint;
        int x = -100;
        int y = -100;
        int width = 100;
        public DrawView(MainActivity context) {
            super(context);
            paint = new Paint();
            paint.setColor(Color.BLUE);
        }
        @Override protected void onDraw(Canvas canvas) {
            drawView.setBackgroundColor(colors[colorIndex]);
            switch (sharpe) {
                case 0:
                    canvas.drawCircle(x - width / 2, y - width / 2, width / 2, paint);
                    break;
                case 1:
                    canvas.drawRect(x - width / 2, y - width / 2, x + width / 2, y + width / 2, paint);
                    break;
                case 2:
                    Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.mipmap.rabbit);
                    canvas.drawBitmap(bitmap, x, y, paint);
                    break;
            }
            super.onDraw(canvas);
        }
    }
}